package com.example.newsapp.ui.components.otherComponent.drawerComponent

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusModifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import com.example.newsapp.data.list.drawContent
import com.example.newsapp.data.list.fontColors
import com.example.newsapp.data.`object`.PageNavigation
import com.example.newsapp.data.`object`.StateSave
import kotlinx.coroutines.delay
import kotlin.random.Random

// 侧边栏内容
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DrawContext(modifier: Modifier = Modifier) {
    var context = LocalContext.current
    var screenWidth = LocalConfiguration.current.screenWidthDp.dp
    var isAlertDialog by rememberSaveable { mutableStateOf(false) }
    var currentColorIndex by rememberSaveable { mutableStateOf(0) }
    var targetValue = fontColors[currentColorIndex]
    val animationColor by animateColorAsState(targetValue = targetValue)

    // 每隔1s变换一种颜色
    LaunchedEffect(Unit) {
        while (true) {
            delay(1000)
            currentColorIndex = (currentColorIndex + Random.nextInt(1, 5)) % fontColors.size
        }
    }

    ModalDrawerSheet(
        modifier = Modifier.width(screenWidth * 3 / 4)
    ) {
        TopAppBar(
            title = {
                Text(
                    text = "快捷应用导航",
                    modifier = Modifier.fillMaxWidth(),
                    textAlign = TextAlign.Center,
                    fontWeight = FontWeight.Bold,
                    color = animationColor
                )
            }
        )
        LazyColumn {
            items(drawContent) {
                val pointerIcon = it.pointer
                val logoIcon = it.logo
                val title = it.title
                val packageName = it.packageName
                val url = it.url
                var colorIndexScope by rememberSaveable { mutableStateOf(0) }
                var targetValueScope = fontColors[colorIndexScope]
                val animationColorScope by animateColorAsState(targetValue = targetValueScope)

                // 每隔1s变换一种颜色
                LaunchedEffect(Unit) {
                    while (true) {
                        delay(1000)
                        colorIndexScope = (colorIndexScope + Random.nextInt(1, 5)) % fontColors.size
                    }
                }

                val pointer = rememberAsyncImagePainter(
                    model = ImageRequest.Builder(context)
                        .data("file:///android_asset/imageIcons/${pointerIcon}")
                        .build()
                )
                val logo = rememberAsyncImagePainter(
                    model = ImageRequest.Builder(context)
                        .data("file:///android_asset/imageIcons/${logoIcon}")
                        .build()
                )
                NavigationDrawerItem(
                    label = {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.Center,
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text(
                                text = "${title}",
                                fontSize = 20.sp
                            )
                        }
                    },
                    icon = {
                        Icon(
                            painter = pointer,
                            contentDescription = null,
                            tint = animationColorScope,
                            modifier = Modifier.size(25.dp)
                        )
                    },
                    badge = {
                        Image(
                            painter = logo,
                            contentDescription = null,
                            modifier.size(25.dp)
                        )
                    },
                    selected = false,
                    onClick = {
                        // 跳转到其他应用
                        val intent = Intent(Intent.ACTION_VIEW)
                        StateSave.alertTitle = title
                        StateSave.packageName = packageName
                        try {
                            intent.setData(Uri.parse(url))
                            context.startActivity(intent)
                        } catch (e: Exception) {
                            isAlertDialog = true
                        }
                    }
                )
            }
            // 如果应用未安装则跳转到应用商店
            item {
                if (isAlertDialog) {
                    AlertDialog(
                        onDismissRequest = { isAlertDialog = false },
                        text = {
                            Text(
                                text ="你还未安装${StateSave.alertTitle}",
                                modifier = Modifier.fillMaxWidth(),
                                textAlign = TextAlign.Center,
                                fontSize = 20.sp
                            )

                        },
                        dismissButton = {
                            TextButton(
                                onClick = { isAlertDialog = false }
                            ) {
                                Text("取消")
                            }
                        },
                        confirmButton = {
                            TextButton(
                                onClick = {
                                    var uri = Uri.parse("market://details?id=${StateSave.packageName}")
                                    var intent = Intent(Intent.ACTION_VIEW, uri)
                                    context.startActivity(intent)
                                }
                            ) {
                                Text("去安装${StateSave.alertTitle}")
                            }
                        }
                    )
                }
            }
        }
    }
}